package cn.stazxr;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Package: cn.stazxr
 * 动态时钟
 *
 * @Author: stazxr
 * @Create: 2023/12/12
 * @Version: v1.0
 **/
public class DynamicClock {

    // 标识位
    private static boolean flag = true;

    public static void main(String[] args) {
        JFrame frame = new JFrame("动态时钟 作者：stazxr.cn");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(350, 230));
        frame.setLocationRelativeTo(null);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.setColor(Color.WHITE);
                g.setFont(new Font("微软雅黑", Font.BOLD, 40));
                g.drawString("当前时间：", 10, 50);
            }
        };
        panel.setBackground(Color.BLACK);
        panel.setBounds(0, 0, 350, 60);
        frame.add(panel);

        ClockPanel comp = new ClockPanel();
        comp.setBounds(0, 60, 350, 140);
        frame.add(comp);

        frame.setVisible(true);
        Thread thread = new Thread(() -> {
            while (flag) {
                comp.repaint();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                //  结束线程
                flag = false;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
                thread.interrupt();
            }
        });

        thread.start();

        while (!thread.isInterrupted()) {
            Thread.yield();
        }
        System.out.println("exited");
    }

    private static class ClockPanel extends Component {

        private static final SimpleDateFormat DATE_FORMAT;
        private static final SimpleDateFormat TIME_FORMAT;

        static {
            DATE_FORMAT = new SimpleDateFormat("yyyy'年'MM'月'dd'日'");
            TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑", Font.BOLD, 30));
            g.drawString(DATE_FORMAT.format(Calendar.getInstance().getTime()), 20, 100);
            g.drawString(TIME_FORMAT.format(Calendar.getInstance().getTime()), 20, 140);
        }
    }
}
